package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgy.ysq.core.web.FriendCode;
import com.sgy.ysq.wx.client.WxSecurityCheckClient;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.liuwu.commons.exception.BusinessException;

import java.io.File;
import java.util.HashMap;

public class WxSecurityCheckClientImpl implements WxSecurityCheckClient {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ObjectMapper objectMapper;

    public WxSecurityCheckClientImpl() {
        objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @Override
    public Boolean msgSecCheck(String accessToken,String content) {
        // 请求地址
        String url = String.format("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s", accessToken);

        // http 请求头设置
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(1000);
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json");

        // 组装参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("content", content);

        // 转换设置参数
        String jsonStr = JSONObject.toJSONString(paramMap);
        RequestEntity requestEntity = new StringRequestEntity(jsonStr);
        method.setRequestEntity(requestEntity);

        try {
            // 执行请求
            client.executeMethod(method);

            // 返回请求,判断状态
            if (method.getStatusCode() == HttpStatus.SC_OK) {// 请求成功,状态200
                String responseStr = method.getResponseBodyAsString();
                JSONObject jsonObject = JSON.parseObject(responseStr);
                Object errcode = jsonObject.get("errcode");
                Object errMsg = jsonObject.get("errmsg");
                if ( errcode!=null && "0".equals(errcode.toString())&& errMsg!=null && "ok".equals(errMsg)){
                    return true;
                }else if(errMsg!=null){
                    throw new BusinessException(FriendCode.WX_CHECK,errMsg.toString());
                }
            } else {// 请求失败
                throw new BusinessException(FriendCode.PRESENCE_SENSITIVE_VOCABULARY);
            }
        } catch (Exception e) {
            logger.error(String.format("msgSecCheck 异常:%s", e.getMessage()), e);
            throw new BusinessException(FriendCode.PRESENCE_SENSITIVE_VOCABULARY);
        }
        return false;
    }

    @Override
    public Boolean imgSecCheck(String accessToken, File file) {
        try{
            // 请求地址
            String url = String.format("https://api.weixin.qq.com/wxa/img_sec_check?access_token=%s", accessToken);

            org.apache.http.client.HttpClient httpClient =  HttpClientBuilder.create().build();

            HttpPost httpPost = new HttpPost(url);

            HttpEntity httpEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532)
                    .addBinaryBody("media", file, ContentType.DEFAULT_BINARY, file.getName()).build();
            httpPost.setEntity(httpEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                HttpEntity resEntity = response.getEntity();
                String data = EntityUtils.toString(resEntity);
                System.out.println(data);
                JSONObject jsonObject = JSON.parseObject(data);
                Object errcode = jsonObject.get("errcode");
                Object errMsg = jsonObject.get("errmsg");
                if ( errcode!=null && "0".equals(errcode.toString())&& errMsg!=null && "ok".equals(errMsg)){
                    return true;
                }else if(errMsg!=null){
                    throw new BusinessException(FriendCode.WX_CHECK,errMsg.toString());
                }
            }
            throw new BusinessException(FriendCode.WX_CHECK,"微信验证图片失败");
        }catch (Exception e){
            throw new BusinessException(FriendCode.WX_CHECK,e.getMessage());
        }
    }

    @Override
    public void mediaCheckAsync() {
    }

}
